﻿using Mengsk.ProxyDelivery.App.Domain;
using Mengsk.ProxyDelivery.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using Mengsk.ProxyDelivery.Service;

namespace Mengsk.ProxyDelivery.App.UI.Goods
{
    /// <summary>
    /// GoodsSkuEditWindow.xaml 的交互逻辑
    /// </summary>
    public partial class GoodsSkuEditWindow : Window
    {
        private ShoesService shoesService = ServiceContainer.GetService<ShoesService>();
        private ShoesSkuService shoesSkuService = ServiceContainer.GetService<ShoesSkuService>();
        private System.Collections.ObjectModel.ObservableCollection<ColorTypeVM> allColorTypes = new System.Collections.ObjectModel.ObservableCollection<ColorTypeVM>();
        private System.Collections.ObjectModel.ObservableCollection<ShoesSkuGroupVM> skuGroups = new System.Collections.ObjectModel.ObservableCollection<ShoesSkuGroupVM>();
        SizeTypeVM[] sizeTypes = "31,32,33,34,35,36,37,38,39,40,41,42,43,44,45".Split(',').Select(obj => new SizeTypeVM() { Size = obj, IsChecked = false }).ToArray();

        private bool isloaded = false;

        public Shoes Shoes { get; set; }

        public TextBox[] GetEdtionTextBoxs()
        {
            return new TextBox[] { this.tbEdtion0, this.tbEdtion1, this.tbEdtion2, this.tbEdtion3, this.tbEdtion4, this.tbEdtion5 };
        }

        public GoodsSkuEditWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //填充版本
            IList<ShoesSku> shoesSkus = this.shoesSkuService.GetAllByField("shoesId", this.Shoes.Id, 0, 0).Datas;
            string[] edtions = shoesSkus.Select(obj => obj.Edtion).Distinct().ToArray();
            TextBox[] tbs = this.GetEdtionTextBoxs();
            for (int i = 1; i < tbs.Length && i < edtions.Length; i++)
            {
                tbs[i].Text = edtions[i];
            }
            //生成颜色
            var systemColors = Mengsk.ProxyDelivery.App.Service.ColorTypeService.GetAllColorTypes();
            var skuColors = shoesSkus.Select(obj => obj.Color).Distinct().ToArray();
            var unNormalColors = skuColors.Where(color => systemColors.Any(c => c.Name == color) == false).Distinct().ToArray();
            var colors2 = skuColors.Select(c => new ColorType(c, "FFF"));
            List<ColorType> colorTypes = new List<ColorType>(systemColors);
            colorTypes.AddRange(unNormalColors.Select(obj => new ColorType(obj, "FFF")));
            for (int i = 0; i < colorTypes.Count; i++)
            {
                colorTypes[i].Id = i + 1;
            }
            foreach (var color in colorTypes.Select(obj => new ColorTypeVM(obj, false)))
            {
                this.allColorTypes.Add(color);
                color.IsChecked = skuColors.Any(obj => obj == color.Title);
            }
            this.lstColorTypes.ItemsSource = this.allColorTypes;
            //尺码
            foreach (var chkSize in sizeTypes)
            {
                chkSize.IsChecked = shoesSkus.Select(obj => obj.Size).Any(c => c.Contains(chkSize.Size));
            }
            this.lstSizes.ItemsSource = sizeTypes;
            this.isloaded = true;

            this.UpdateSkuGroups();
            this.CreateSkus();
            this.lstSkus.ItemsSource = this.skuGroups;
        }

        private void CreateSkus()
        {
            if (this.isloaded == false)
            {
                return;
            }
            SizeTypeVM[] selectedSize = this.sizeTypes.Where(obj => obj.IsChecked).ToArray();
            ColorTypeVM[] selectedColor = this.allColorTypes.Where(obj => obj.IsChecked).ToArray();

            foreach (var group in this.skuGroups)
            {
                var shoesSkus = this.Shoes.Skus.Where(obj => obj.Edtion == group.Edtion || (obj.Edtion == "" && (group.Edtion == "" || group.Edtion == "默认版本")));
                var shoesSkuVMs = shoesSkus.Select(obj => new ShoesSkuVM { Color = obj.Color, Size = obj.Size, Price = obj.Price, OffLinePrice = obj.OffLinePrice });
                foreach (var item in shoesSkuVMs)
                {
                    item.ColorType = this.allColorTypes.First(obj => obj.Title == item.Color);
                    group.ShoesSkus.Add(item);
                }
            }
        }

        private void chkColor_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox cb = sender as CheckBox;
                ColorTypeVM colorType = cb.DataContext as ColorTypeVM;
                string[] sizes = this.sizeTypes.Where(obj => obj.IsChecked).Select(obj => obj.Size).ToArray();

                foreach (var group in this.skuGroups)
                {
                    foreach (string size in sizes)
                    {
                        group.ShoesSkus.Add(new ShoesSkuVM { Color = colorType.Title, Size = size, Price = 0, OffLinePrice = 0, ColorType = colorType });
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chkColor_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox cb = sender as CheckBox;
                ColorTypeVM colorType = cb.DataContext as ColorTypeVM;
                foreach (var group in this.skuGroups)
                {
                    var itemToDelete = group.ShoesSkus.Where(obj => obj.ColorType == colorType).ToArray();
                    foreach (var item in itemToDelete)
                    {
                        group.ShoesSkus.Remove(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tbEdtion_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.UpdateSkuGroups();
        }

        private void UpdateSkuGroups()
        {
            if (this.isloaded == false)
            {
                return;
            }
            TextBox[] tbs = this.GetEdtionTextBoxs();

            foreach (var tb in tbs)
            {
                //删除
                if (tb.DataContext != null && tb.Text.Trim().Length < 1)
                {
                    this.skuGroups.Remove(tb.DataContext as ShoesSkuGroupVM);
                    tb.DataContext = null;
                }
                //创建
                else if (tb.DataContext == null && tb.Text.Trim().Length > 0)
                {
                    var shoesSkuGroup = new ShoesSkuGroupVM(tb.Text.Trim());
                    tb.DataContext = shoesSkuGroup;
                    this.skuGroups.Add(shoesSkuGroup);
                    //复制基本版本信息
                    if (tb != tbs[0])
                    {
                        foreach (var item in (tbs[0].DataContext as ShoesSkuGroupVM).ShoesSkus)
                        {
                            shoesSkuGroup.ShoesSkus.Add(item.Clone() as ShoesSkuVM);
                        }
                    }
                }
                //更新名称
                else if (tb.DataContext != null && tb.Text.Trim().Length > 0)
                {
                    (tb.DataContext as ShoesSkuGroupVM).Edtion = tb.Text.Trim();
                }
            }
        }


        private void chkSize_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox cb = sender as CheckBox;
                string size = cb.Content.ToString();
                ColorTypeVM[] selelctedColorTypes = this.allColorTypes.Where(obj => obj.IsChecked).ToArray();

                foreach (var group in this.skuGroups)
                {
                    foreach (var colorType in selelctedColorTypes)
                    {
                        group.ShoesSkus.Add(new ShoesSkuVM { Color = colorType.Title, Size = size, Price = 0, OffLinePrice = 0, ColorType = colorType });
                    }
                    var newList = group.ShoesSkus.OrderBy(obj => obj.Color).ToArray();
                    group.ShoesSkus.Clear();
                    foreach (var item in newList)
                    {
                        group.ShoesSkus.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chkSize_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                CheckBox cb = sender as CheckBox;
                string size = cb.Content.ToString();

                foreach (var group in this.skuGroups)
                {
                    var itemToDelete = group.ShoesSkus.Where(obj => obj.Size == size).ToArray();
                    foreach (var item in itemToDelete)
                    {
                        group.ShoesSkus.Remove(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<ShoesSku> shoesSkus = new List<ShoesSku>();
                foreach (var group in this.skuGroups)
                {
                    shoesSkus.AddRange(group.ShoesSkus.Select(obj => new ShoesSku { Edtion = group.Edtion == "默认版本" ? "" : group.Edtion, Color = obj.Color, Size = obj.Size, Price = obj.Price, OffLinePrice = obj.OffLinePrice, ShoesId = this.Shoes.Id }));
                }

                shoesSkus.ForEach(obj =>
                {
                    if (obj.Price == 0 || obj.OffLinePrice == 0)
                    {
                        throw new Exception("商品价格不正确:" + obj.Edtion + "  " + obj.Color + "  " + obj.Size);
                    }
                });
                this.Shoes.Skus.Clear();
                this.Shoes.Skus.AddRange(shoesSkus);
                this.shoesService.UpdateWithSku(this.Shoes);
                MessageBox.Show("已成功保存");
                this.DialogResult = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
